<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的书柜</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='bookshelf.css') }}">
    <style>
        /* 添加按钮样式 */
        .header-buttons {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        }
        .header-button {
            background-color: #979797; /* 绿色 */
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin-left: 10px;
            cursor: pointer;
            border-radius: 4px;
            transition-duration: 0.4s;
        }
        .header-button:hover {
            background-color: white;
            color: black;
            border: 2px solid #4CAF50;
        }

        .modal2 {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            display: none;
            background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
        }

        .modal-content2 {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 400px;
            max-height: 70%;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            padding: 20px;
            overflow-y: auto; /* 启用垂直滚动 */
        }

        .modal {
            display: none; /* 默认隐藏模态框 */
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4); /* 半透明黑色背景 */
        }

        /* 模态窗口内容 */
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto; /* 居中显示 */
            padding: 20px;
            border-radius: 8px; /* 圆角边框 */
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
            max-width: 400px; /* 设置最大宽度 */
            width: 90%; /* 自适应宽度 */
        }

        /* 关闭按钮 */
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
        }

        /* 标题样式 */
        .modal h3 {
            font-size: 24px;
            margin-bottom: 20px;
            color: #333;
        }

        /* 输入框样式 */
        #new-bookshelf-name {
            width: calc(100% - 22px); /* 宽度自适应 */
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 下拉选择框样式 */
        #bookshelf-select {
            width: calc(100% - 22px); /* 宽度自适应 */
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 按钮样式 */
        .modal button {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .modal button:hover {
            background-color: #45a049;
        }

        .add-card {
            position: fixed;
            bottom: 100px;
            right: 20px;
            background-color: #ff6347;
            color: #fff;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav>
        <!-- 保留现有导航栏样式和内容 -->
    </nav>

    <!-- 新增按钮容器 -->
    <div class="header-buttons">
        <button id="create-bookshelf-btn" class="header-button">创建</button>
        <button id="switch-bookshelf-btn" class="header-button">切换</button>
    </div>

    <div class="container">
        <!-- 书柜标题 -->
        <h2 id="bookshelf-title">默认书柜</h2>

        <!-- 书柜内容区域 -->
        <div id="bookshelf-content" class="bookshelf"></div>

        <!-- 加号按钮 -->
        <div class="add-card" onclick="showModal()">
            <span class="add-icon">+</span>
        </div>
    </div>

    <!-- 添加书籍模态窗口 -->
    <div id="modal" class="modal2">
        <div class="modal-content2">
            <span class="close" onclick="closeModal()">&times;</span>
            <div id="book-selection" class="content">加载中...</div>
        </div>
    </div>

    <!-- 创建书柜模态窗口 -->
    <div id="create-modal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeCreateModal()">&times;</span>
            <h3>创建新书柜</h3>
            <input type="text" id="new-bookshelf-name" placeholder="输入书柜名称" required>
            <button onclick="createBookshelf()">创建</button>
        </div>
    </div>

    <!-- 切换书柜模态窗口 -->
    <div id="switch-modal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeSwitchModal()">&times;</span>
            <h3>切换书柜</h3>
            <select id="bookshelf-select"></select>
            <button onclick="switchToSelectedBookshelf()">切换</button>
        </div>
    </div>

    <!-- 底部导航栏 -->
    {% include 'footer.html' %}

    <script>
        let bookshelf_id = null;
        let books = [];
        let user_bookshelves = [];

        window.onload = function() {
            fetchBookshelf(); // 页面加载时加载书柜
            fetchUserBookshelves(); // 加载用户的书柜列表
        };

        async function fetchBookshelf(bookshelfId) {
            try {
                const response = await fetch(`/get_bookshelf?bookshelf_id=${bookshelfId || bookshelf_id}`);
                if (!response.ok) {
                    throw new Error("无法获取书柜信息");
                }
                const data = await response.json();
                if (data.bookshelf_id && data.name) { // 确保有 name 字段
                    bookshelf_id = data.bookshelf_id;
                    document.getElementById('bookshelf-title').innerText = data.name; // 显示书柜名称
                    books = data.books;
                    loadBookshelf(books);
                } else {
                    alert('没有找到书柜');
                }
            } catch (error) {
                console.error("获取书柜数据时出错:", error);
            }
        }

        function loadBookshelf(books) {
            const bookshelfContent = document.getElementById('bookshelf-content');
            bookshelfContent.innerHTML = '';
            books.forEach((book) => {
                const card = document.createElement('div');
                card.className = 'card';
                card.innerHTML = `
                    <a href="/book/${book.id}" class="book-link">
                        <img src="${book.image}" alt="${book.title}">
                        <h3>${book.title}</h3>
                    </a>
                    <button onclick="removeFromBookshelf(${book.id})" class="remove-button">移出</button>
                `;
                bookshelfContent.appendChild(card);
            });
        }

        // 定义一次 showModal 和 closeModal 函数
        function showModal() {
            document.getElementById('modal').style.display = 'block';
            loadBookSelection();
        }

        function closeModal() {
            document.getElementById('modal').style.display = 'none';
        }

        async function loadBookSelection() {
            try {
                const response = await fetch('/api/books');
                const availableBooks = await response.json();
                const bookSelection = document.getElementById('book-selection');
                bookSelection.innerHTML = '';
                availableBooks.forEach(book => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <img src="${book.image}" alt="${book.title}">
                        <h3>${book.title}</h3>
                        <button onclick='addToBookshelf(${book.id})'>添加</button>
                    `;
                    bookSelection.appendChild(card);
                });
            } catch (error) {
                console.error("加载可选书籍时出错:", error);
            }
        }

        async function addToBookshelf(bookId) {
            if (books.some(book => book.id === bookId)) {
                alert("书籍已在书柜中");
                closeModal();
                return;
            }

            try {
                const response = await fetch('/add_to_bookshelf', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ bookshelf_id, book_id: bookId }),
                });
                const data = await response.json();
                if (data.success) {
                    // 使用当前的 bookshelf_id 刷新书柜内容
                    fetchBookshelf(bookshelf_id);
                    closeModal(); // 自动关闭弹窗
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error("添加书籍时出错:", error);
            }
        }


        function loadBookshelf(books) {
            const bookshelfContent = document.getElementById('bookshelf-content');
            bookshelfContent.innerHTML = '';
            books.forEach((book) => {
                const card = document.createElement('div');
                card.className = 'card';
                card.innerHTML = `
                    <a href="/book/${book.id}" class="book-link">
                        <img src="${book.image}" alt="${book.title}">
                        <h3>${book.title}</h3>
                    </a>
                    <button onclick="removeFromBookshelf(${book.id})" class="remove-button">移出</button>
                `;
                bookshelfContent.appendChild(card);
            });
        }

        async function loadBookSelection() {
            try {
                const response = await fetch('/api/books');
                const availableBooks = await response.json();
                const bookSelection = document.getElementById('book-selection');
                bookSelection.innerHTML = '';
                availableBooks.forEach(book => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <img src="${book.image}" alt="${book.title}">
                        <h3>${book.title}</h3>
                        <button onclick='addToBookshelf(${book.id})'>添加</button>
                    `;
                    bookSelection.appendChild(card);
                });
            } catch (error) {
                console.error("加载可选书籍时出错:", error);
            }
        }

        async function addToBookshelf(bookId) {
            if (books.some(book => book.id === bookId)) {
                alert("书籍已在书柜中");
                closeModal();
                return;
            }

            try {
                const response = await fetch('/add_to_bookshelf', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ bookshelf_id, book_id: bookId }),
                });
                const data = await response.json();
                if (data.success) {
                    fetchBookshelf();
                    closeModal(); // 自动关闭弹窗
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error("添加书籍时出错:", error);
            }
        }

        async function removeFromBookshelf(bookId) {
            if (!books.some(book => book.id === bookId)) {
                alert("书籍不在书柜中，无法移出");
                return;
            }

            try {
                const response = await fetch('/remove_from_bookshelf', {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ bookshelf_id, book_id: bookId }),
                });
                const data = await response.json();
                if (data.success) {
                    alert("书籍已成功移出书柜");
                    fetchBookshelf();
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error("移出书籍时出错:", error);
            }
        }

        // 创建书柜
        document.getElementById('create-bookshelf-btn').addEventListener('click', () => {
            document.getElementById('create-modal').style.display = 'block';
        });

        // 关闭创建书柜模态窗口
        function closeCreateModal() {
            document.getElementById('create-modal').style.display = 'none';
        }

        // 实现创建书柜功能
        async function createBookshelf() {
            const name = document.getElementById('new-bookshelf-name').value.trim();
            if (!name) {
                alert("请为书柜命名！");
                return;
            }

            try {
                const response = await fetch('/create_bookshelf', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name }),
                });
                const data = await response.json();
                if (data.success) {
                    alert("新书柜创建成功！");
                    fetchUserBookshelves(); // 更新书柜列表
                    closeCreateModal();
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error("创建书柜时出错:", error);
            }
        }

        // 获取用户的书柜列表
        async function fetchUserBookshelves() {
            try {
                const response = await fetch('/user_bookshelves');
                const data = await response.json();
                user_bookshelves = data.bookshelves;
                populateBookshelfSelect();
            } catch (error) {
                console.error("获取书柜列表时出错:", error);
            }
        }

        // 填充切换书柜的选择框
        function populateBookshelfSelect() {
            const selectElement = document.getElementById('bookshelf-select');
            selectElement.innerHTML = ''; // 清空选项
            user_bookshelves.forEach(bookshelf => {
                const option = document.createElement('option');
                option.value = bookshelf.id;
                option.text = `${bookshelf.name}`;
                selectElement.appendChild(option);
            });
        }

        // 打开切换书柜模态窗口
        document.getElementById('switch-bookshelf-btn').addEventListener('click', () => {
            document.getElementById('switch-modal').style.display = 'block';
        });

        // 关闭切换书柜模态窗口
        function closeSwitchModal() {
            document.getElementById('switch-modal').style.display = 'none';
        }

        // 切换到选定的书柜
        async function switchToSelectedBookshelf() {
            const selectedId = document.getElementById('bookshelf-select').value;
            if (selectedId) {
                fetchBookshelf(parseInt(selectedId));
                closeSwitchModal();
            }
        }
    </script>
</body>
</html>